/*
** broadcast.c for Broadcast in /home/vriely/Dropbox/work/Unix/Zappy_rendu/serv-src
**
** Made by Samuel Vrielynck
** Login   <vriely_s@epitech.net>
**
** Started on  Thu Jul 05 13:14:32 2012 Samuel Vrielynck
** Last update Wed Jul 18 19:50:53 2012 Samuel Vrielynck
*/

#include	<stdlib.h>
#include	<math.h>

#include	"server.h"

static int	return_un(double a)
{
  if (a < 18.42 && a > -18.42)
    return (1);
  if (a < 71.56 && a > 18.42)
    return (8);
  if (a > -71.56 && a < -18.42)
    return (2);
  if (a > 71.56)
    return (7);
  if (a < -71.56)
    return (3);
  return (0);
}

static int	return_deux(double a)
{
  if (a < 18.42 && a > -18.42)
    return (5);
  if (a < 71.56 && a > 18.42)
    return (4);
  if (a > -71.56 && a < -18.42)
    return (6);
  if (a > 71.56)
    return (3);
  if (a < -71.56)
    return (7);
  return (0);
}

static char	get_k(t_coord *dest, t_coord *src, unsigned char dir)
{
  double	a;
  double	rad;
  double	tmp;
  int		tmpy;
  int		tmpx;

  if (dest->x == src->x && dest->y == src->y)
    return (0);
  else if (dest->x == src->x && dest->y > src->y)
    return (orientation(3, dir));
  else if (dest->x == src->x && dest->y < src->y)
    return (orientation(7, dir));
  tmpy = dest->y - src->y;
  tmpx = dest->x - src->x;
  tmp = (double)tmpy / (double)tmpx;
  rad = atan(tmp);
  a = 180 * rad / M_PI;
  if (dest->x < src->x)
    return (orientation(return_un(a), dir));
  else
    return (orientation(return_deux(a), dir));
  return (0);
}

static void	broadcast_client(void *content, void *data)
{
  t_client	*client;
  t_broadcast	*broadcast;

  client = (struct s_client *)content;
  if (client->gamer != NULL)
  {
    broadcast = (struct s_broadcast *)data;
    if (broadcast->client != client)
    {
      client->send->concat(client->send, "message ");
      client->send->concat_value(client->send, get_k(&client->gamer->coord, \
	    &broadcast->coord, client->gamer->direction));
      client->send->concat(client->send, ",");
      client->send->concat(client->send, broadcast->message + 1);
      client->send->concat(client->send, "\n");
    }
  }
}

char		handle_broadcast(t_event *event, t_game *game, t_list *clients,
    long unsigned int elapsed_time)
{
  t_broadcast*	broadcast;

  broadcast = (struct s_broadcast*)event->data;
  if (broadcast->client && broadcast->client->gamer &&
      is_alive(game->time, *(broadcast->client->gamer), elapsed_time))
    clients->foreach(clients, &broadcast_client, event->data);
  free(broadcast->message);
  free(broadcast);
  return (1);
}
